package com.example.microinvestcommon.util;

import org.springframework.stereotype.Component;

import java.util.concurrent.atomic.AtomicInteger;

@Component
public class SnowflakeIdGeneratorUtil {
    private static final long TWEPOCH = 1700000000L; // 2023-11-14 的秒级时间戳
    private static final long WORKER_ID_BITS = 3L;
    private static final long SEQUENCE_BITS = 8L;

    private static final long MAX_WORKER_ID = ~(-1L << WORKER_ID_BITS);
    private static final long SEQUENCE_MASK = ~(-1L << SEQUENCE_BITS);

    private static final long WORKER_ID_SHIFT = SEQUENCE_BITS;
    private static final long TIMESTAMP_LEFT_SHIFT = SEQUENCE_BITS + WORKER_ID_BITS;

    private final long workerId;
    private long lastTimestamp = -1L;
    private final AtomicInteger sequence = new AtomicInteger(0);

    public SnowflakeIdGeneratorUtil(long workerId) {
        if (workerId > MAX_WORKER_ID || workerId < 0) {
            throw new IllegalArgumentException("Worker ID 超出范围");
        }
        this.workerId = workerId;
    }

    public synchronized long nextId() {
        long timestamp = System.currentTimeMillis() / 1000; // 使用秒级时间戳

        if (timestamp < lastTimestamp) {
            throw new RuntimeException("时钟回拨异常");
        }

        if (lastTimestamp == timestamp) {
            int seq = (sequence.incrementAndGet()) & (int) SEQUENCE_MASK;
            if (seq == 0) {
                while (timestamp <= lastTimestamp) {
                    timestamp = System.currentTimeMillis() / 1000;
                }
            }
        } else {
            sequence.set(0);
        }

        lastTimestamp = timestamp;

        return ((timestamp - TWEPOCH) << TIMESTAMP_LEFT_SHIFT)
                | (workerId << WORKER_ID_SHIFT)
                | sequence.get();
    }
}
